package com.duapk.search.work;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.duapk.search.conf.ConfigFactory;

/**
 * 线程池管理
 * 
 * @author yangfeng
 * 
 */
public class ThreadPoolManager {

	// 线程池Map
	private static Map<String, ThreadPoolExecutor> threadPoolMap = new HashMap<String, ThreadPoolExecutor>();

	private static final int corePoolSize = ConfigFactory
			.getInt("ThreadPool.corePoolSize");
	private static final int maximumPoolSize = ConfigFactory
			.getInt("ThreadPool.maximumPoolSize");
	private static final int keepAliveTime = ConfigFactory
			.getInt("ThreadPool.keepAliveTime");
	private static final int queueSize = ConfigFactory
			.getInt("ThreadPool.queueSize");

	/**
	 * 创建线程池
	 * 
	 * @Title: createExecutor
	 * @author: jiangzheng
	 * @date: Apr 21, 2011 5:06:02 PM
	 * @param category
	 */
	public static void createExecutor(String category) {
		if (!threadPoolMap.containsKey(category)) {
			ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
					corePoolSize, maximumPoolSize, keepAliveTime,
					TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(
							queueSize), new ThreadPoolExecutor.AbortPolicy());
			threadPoolMap.put(category, threadPool);
		}
	}

	/**
	 * 在分类线程池中执行
	 * 
	 * @param thread
	 * @param category
	 *            分类信息
	 */
	public static void execute(Runnable thread, String category) {

		ThreadPoolExecutor executor = threadPoolMap.get(category);
		while (true) {
			try {
				executor.execute(thread);
				break;
			} catch (RejectedExecutionException e) {
				try {
					Thread.sleep(2);
				} catch (InterruptedException e1) {
				}
				continue;
			}
		}
	}
}
